package com.sdry.service.impl.jyy;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import com.sdry.model.cb.TypeEnum;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sdry.mapper.jyy.ReceiveDetailMapper;
import com.sdry.mapper.jyy.ReceiveMapper;
import com.sdry.model.jyy.Receive;
import com.sdry.model.jyy.ReceiveDetail;
import com.sdry.model.jyy.Up;
import com.sdry.model.llm.LlmRegionStock;
import com.sdry.model.llm.LlmWarehouseStock;
import com.sdry.model.lz.Customer;
import com.sdry.model.lz.Materiel;
import com.sdry.model.lz.ReceiveMark;
import com.sdry.model.lz.WarehouseRegionLocation;
import com.sdry.model.zc.ZcSysUserEntity;
import com.sdry.service.jyy.ReceiveService;
/**
 *
 *@ClassName: ReceiveService
 *@Description: 收货计划
 *@Author jyy
 *@Date 2019-04-18 09:35:01
 *@version 1.0
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class ReceiveServiceImpl implements ReceiveService {
	@Resource ReceiveMapper ReceiveMapper;
	@Resource ReceiveDetailMapper ReceiveDetailMapper;
	/** 
	 * 根据主键id查询实体
	 * @param id 主键id
	 * @return 实体
	*/
	public Receive queryById(Long id) {
		return ReceiveMapper.queryById(id);
	}
	/** 
	 * 条件查询所有
	 * @param param 实体条件
	 * @return 实体集合
	*/
	public List<Receive> queryAllByMution(Receive param) {
		return ReceiveMapper.queryAllByMution(param);
	}
	/** 
	 * 条件分页查询
	 * @param param 实体条件
	 * @return 实体集合
	*/
	public List<Receive> findPageByMution(Receive param) {
		return ReceiveMapper.findPageByMution(param);
	}
	/** 
	 * 条件查询记录数
	 * @param param 实体条件
	 * @return 实体集合
	*/
	public Integer selectCountByMution(Receive param) {
		return ReceiveMapper.selectCountByMution(param);
	}
	/** 
	 * 插入返回id
	 * @param param 实体条件
	 * @return 主键id
	*/
	public Long insert(Receive param) {
		return ReceiveMapper.insert(param);
	}
	/** 
	 * 根据主键更新 返回影响行数
	 * @param param 实体条件
	 * @return 影响行数
	*/
	public Integer update(Receive param) {
		return ReceiveMapper.update(param);
	}
	/** 
	 * 根据主键拼接的字符串删除返回影响行数
	 * @param ids 主键拼接的字符串
	 * @return 影响行数
	*/
	public Integer delete(String ids) {
		return ReceiveMapper.delete(ids);
	}
	/**
	 * 根据物料id查询物料的仓库信息
	 * @param  物料id
	 * @return
	 */
	@Override
	public List<LlmWarehouseStock> selectWarehouseByMid(Up up) {
		
		List<LlmWarehouseStock> list = ReceiveMapper.selectWarehouseByMid(up);
		Long mid = up.getMid();
		Long customerId = up.getCustomerId();
		if(list.size() > 0){
			for(LlmWarehouseStock ws : list){
				ws.setRemark(mid+"");
				ws.setStatus(customerId+"");
				List<LlmRegionStock> regionList = ReceiveMapper.selectRegionStockByWarehouseId(ws);
				if(regionList.size() > 0){
					for(LlmRegionStock rs : regionList){
						rs.setRemark(mid+"");
						rs.setRegion_status(customerId+"");
						List<WarehouseRegionLocation> locationList = ReceiveMapper.selectLocationStockByRegionId(rs);
						rs.setLocationList(locationList);
					}
				}
				ws.setRegionList(regionList);
			}
		}
		return list;
	}
	
	/**
	 * 根据物料产品码查询物料所有信息
	 * @param maNum 物料产品码
	 * @return
	 */
	@Override
	public Materiel selectMaByMaNum(String maNum) {
		return ReceiveMapper.selectMaByMaNum(maNum);
	}
	
	/**
	 * 根据供应商 名称 查询相关物料信息
	 * @param client
	 * @return
	 */
	@Override
	public List<Materiel> materielList(long id) {
		return ReceiveMapper.materielList(id);
	}
	
	/**
	 * 根据物料id查询供应商
	 */
	@Override
	public List<Customer> selectCustomerByMid(Long id) {
		return ReceiveMapper.selectCustomerByMid(id);
	}
	
	/**
	 * 根据物料id查询库区位置
	 */
	@Override
	public Materiel queryMaterielLocationById(Long mid) {
		return ReceiveMapper.queryMaterielLocationById(mid);
	}
	
	/**   
	 * 根据条件查询物料 
	 * @param materiel 物料实体
	 * @return             
	 */
	@Override
	public List<Materiel> queryAllMaterielByParam(Materiel materiel) {
		return ReceiveMapper.queryAllMaterielByParam(materiel);
	}
	/**
	 * 根据条件查询单据（不区分发货单，精简发货）
	 * @param receive
	 * @return
	 */
	public List<Receive> allByMution(Receive receive) {
		return ReceiveMapper.allByMution(receive);
	}
	@Override
	public int restor(Map map) {
		// TODO Auto-generated method stub
		return ReceiveMapper.restor(map);
	}
	@Override
	public int cacel(Map map) {
		// TODO Auto-generated method stub
		return ReceiveMapper.cacel(map);
	}
	@Override
	public int queryCodeNumByid(int id) {
		// TODO Auto-generated method stub
		return ReceiveMapper.queryCodeNumByid(id);
	}
	@Override
	public List<Receive> queryAllByMution1(Receive param) {
		// TODO Auto-generated method stub
		return ReceiveMapper.queryAllByMution1(param);
	}
	@Override
	public Integer selectCountByMution1(Receive param) {
		// TODO Auto-generated method stub
		return ReceiveMapper.selectCountByMution1(param);
	}
	
	/**
	 * 单据合并
	 */
	@Override
	public int merge(HttpSession httpSession, String ids, String receiveNumber) {
		int i = 0;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		String time = df.format(new Date());
        ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
		String userName = su.getUserName();
		//1、根据收货单ID查询收货单详情
		String[] arr = ids.split(",");
		List<ReceiveDetail> detailList = new ArrayList<ReceiveDetail>();
		List<Receive> receiveList = new ArrayList<>();
		for(String id : arr){
			List<ReceiveDetail> list = ReceiveDetailMapper.queryDetailByParentTableId(Long.parseLong(id));
			detailList.addAll(list);
			Receive receive = ReceiveMapper.queryById(Long.parseLong(id));
			receiveList.add(receive);
		}
		//2、遍历收货单详情，同物料，数量合并
		int sum = 0;
		Set<Long> midSet = new HashSet<>();
		for(ReceiveDetail detail : detailList){
			sum += detail.getCodeNum();
			midSet.add(detail.getMid());
		}
		if(sum > 0){
			//这个 返回值代表，收货单详情的收货总数大于0，已经收过货了，不能合并收货单
			i = -5;
		}else{
			//3、把合并的单据都取消了
			Map<String, Object> map = new HashMap<>();
			map.put("cancellation_time", time);
			map.put("cancellation", userName);
			for(String id : arr){
				 map.put("id", Long.valueOf(id));
				 ReceiveMapper.cacel(map);
			}
			//4、生成新的收货单
			String sendNumber = "";
			for(Receive re : receiveList){
				sendNumber += re.getSendNumber() + ",";
			}
			Receive receive = new Receive();
			receive.setCreateName(userName);
			receive.setCreateDate(time);
			receive.setSendNumber(sendNumber);
			receive.setReceiveNumber(receiveNumber);
			receive.setSendCompany(receiveList.get(0).getSendCompany());
			receive.setSendName(receiveList.get(0).getSendName());
			receive.setSendDate(time);
			receive.setState(0);
			receive.setFlag("2");
			Long isSuccess = ReceiveMapper.insert(receive);
			if(isSuccess > 0){
				//5、生成新的收货单详情
				ReceiveDetail receiveDetail = new ReceiveDetail();
				receiveDetail.setReceiveNumber(receiveNumber);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				receiveDetail.setPici(sdf.format(new Date()));
				//5.1、遍历每一种物料，对发货数量合计，把收货单详情ID也统计
				for(Long mid : midSet){
					int sumXiang = 0;
					int sumGe = 0;
					int sumZong = 0;
					List<Long> detailIds = new ArrayList<>();
					for(ReceiveDetail rd : detailList){
						if(mid.equals(rd.getMid())){
							sumXiang += rd.getSendNum();
							sumGe = rd.getSingleNum();
							sumZong += rd.getTotalNum();
							detailIds.add(rd.getId());
						}
					}
					receiveDetail.setSendNum(sumXiang);
					receiveDetail.setSingleNum(sumGe);
					receiveDetail.setTotalNum(sumZong);
					receiveDetail.setMid(mid);
					//5.2、把合计后物料信息存入新的收货单详情
					Long detailId = ReceiveDetailMapper.insert(receiveDetail);
					if(detailId > 0){
						//5.3、找到该物料对应的所有条码
						List<ReceiveMark> codeList = new ArrayList<>();
						for(Long id : detailIds){
							List<ReceiveMark> marks = ReceiveDetailMapper.queryReceiveCodeByReceiveDetailId(id.toString());
							codeList.addAll(marks);
						}
						//5.4、把条码绑定到新生成的详情ID
						for(ReceiveMark rm : codeList){
							rm.setReceive_detail_id(detailId);
							ReceiveDetailMapper.addReceiveMark(rm);
						}
						i = 1;
					}else{
						i = -1;
					}
				}
			}else{
				i = -1;
			}
		}
		return i;
	}
	@Override
	public List<Receive> queryAllByMution11(Receive param) {
		// TODO Auto-generated method stub
		return ReceiveMapper.queryAllByMution11(param);
	}
	@Override
	public Integer selectCountByMution11(Receive param) {
		// TODO Auto-generated method stub
		return ReceiveMapper.selectCountByMution11(param);
	}
}
